package com.mtw.bbs.bbsUser.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mtw.bbs.bbsUser.pojo.entity.RoleResource;
import com.mtw.bbs.bbsUser.service.RoleResourceService;
import com.mtw.bbs.bbsUser.service.RoleService;
import com.mtw.bbs.common.core.constant.ServiceConstant;
import com.mtw.bbs.common.core.constant.SysConstant;
import com.mtw.bbs.userAdmin.pojo.vo.RoleVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mtw.bbs.bbsUser.mapper.ResourceAPIMapper;
import com.mtw.bbs.bbsUser.pojo.entity.ResourceAPI;
import com.mtw.bbs.bbsUser.service.ResourceAPIService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 资源逻辑层
 * @author mo
 * @email mo
 * @date 2023-10-18 15:44:13
 */
@RequiredArgsConstructor
@Service("resourcesService")
public class ResourceAPIServiceImpl extends ServiceImpl<ResourceAPIMapper, ResourceAPI> implements ResourceAPIService {


    private final RoleService roleService;
    private final RoleResourceService roleResourceService;




    /**
     * 根据userId查询角色拥有的资源api
     *
     */
    @Override
    public List<ResourceAPI> queryResourceByUserId(String userId) {
        List<RoleVo> roles = roleService.queryByUserId(userId);
        if (CollectionUtils.isEmpty(roles)){
            return new ArrayList<>(1);
        }
        //提取用户所拥有角色id列表
        Set<String> roleIds = roles.stream().map(RoleVo::getId).collect(Collectors.toSet());
        return  this.queryByRoleId(roleIds);
    }


    /**
     * 根据角色Id查询角色拥有的资源
     *
     */
    @Override
    public List<ResourceAPI> queryByRoleId(Collection<String> roleIds) {
        //根据角色列表查询到角色的资源的关联关系
        List<RoleResource> roleResources = roleResourceService.queryByRoleIds(roleIds);
        if (CollectionUtils.isEmpty(roleResources)){
            return new ArrayList<>(1);
        }
        //根据资源列表查询出所有资源对象
        Set<String> resourceIds = roleResources.stream().map(RoleResource::getResourceId).collect(Collectors.toSet());
        LambdaQueryWrapper<ResourceAPI> lqw = new LambdaQueryWrapper<>();
        lqw.select(ResourceAPI::getId,ResourceAPI::getMethod,ResourceAPI::getUrl,ResourceAPI::getType);
        lqw.in(ResourceAPI::getId,resourceIds);
        lqw.eq(ResourceAPI::getStatus, ServiceConstant.STATUS_ENABLE);
        return  list(lqw);
    }




    /**
     * 删除资源信息
     */
    @Override
    @Transactional
    public boolean delete(String[] ids) {
        if (ids== null || ids.length <1){
            return false;
        }
        List<String> list = Arrays.asList(ids);
        roleResourceService.remove(new LambdaQueryWrapper<RoleResource>().in(RoleResource::getResourceId,list));
        return removeBatchByIds(list);
    }


}
